package com.gitee.somenvm.ninerpgitem.core.resolver

object StringListParser {

    val regex = Regex("\\{(.*?):(.*?)\\}")

    fun parse(strings: List<String>, context: Context): List<String> {
        return strings.flatMap { parseString(it, context) }
    }

    fun parseString(source: String, context: Context): List<String> {
        val regex = regex
        val lines = mutableListOf(source)
        var modified = true
        var loopCount = 0

        while (modified && loopCount < 5) {
            modified = false
            val temps = mutableListOf<String>()
            lines.forEachIndexed { i, result ->
                val matches = regex.findAll(result).toList()

                if (matches.isEmpty()) return@forEachIndexed

                for (match in matches) {
                    val (method, placeholder) = match.destructured
                    val resolver = PlaceholderResolver.getResolver(method)

                    // 如果方法名不存在，替换为 <Unknown>
                    temps += resolver?.resolve(result, placeholder, context)
                        ?: listOf(result.replace("{$method:$placeholder}", "&c<未实现的方法=$method>&f"))
                    modified = true
                }
            }
            if (temps.isNotEmpty()) {
                lines.clear()
                lines.addAll(temps)
            }
            loopCount++
        }

        return lines
    }

    // 使用 StringBuilder 进行优化后
//    private fun parseString(source: String, context: Context): List<String> {
//        val regex = Regex("\\{(.*?):(.*?)\\}")
//        val matches = regex.findAll(source).toList()
//
//        if (matches.isEmpty()) {
//            return listOf(source) // 保持初始情况一致
//        }
//
//        var result = source
//        var modified = true
//        var loopCount = 0
//
//        while (modified && loopCount < 5) {
//            modified = false
//            val newResult = StringBuilder(result)
//
//            for (match in matches) {
//                val (method, placeholder) = match.destructured
//                val resolver = PlaceholderResolver.getResolver(method)
//
//                // 如果方法名不存在，替换为 <Unknown>
//                val replacement = resolver?.resolve(result, placeholder, context)
//                    ?: Unknown.resolve(result, placeholder, context)
//
//                val start = match.range.first
//                val end = match.range.last + 1
//                newResult.replace(start, end, replacement)
//                modified = true
//            }
//
//            if (!modified) break
//            result = newResult.toString()
//            loopCount++
//        }
//
//        // 分割结果字符串为多行
//        return result.split("\n")
//    }
}
